package fr.capsuleaube.android;

import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import fr.capsuleaube.android.bean.Producteur;
import fr.capsuleaube.android.fragment.CapsuleDetailFragment;
import fr.capsuleaube.android.fragment.CapsulePhotoFragment;
import fr.capsuleaube.android.fragment.ProducteurListFragment;
import fr.capsuleaube.android.utils.Consts;

public class MainActivity extends ActionBarActivity implements ProducteurListFragment.OnProducteurSelectedListener, CapsulePhotoFragment.OnPhotoSelectedListener {

    // Vrai si l'activité est lancée suite à une recherche par l'utilisateur
    private boolean mIsSearchActivity = false;
    // Vrai si l'activité est exécuté sur un grand écran
    private boolean mIsDualPane = false;

    private FragmentManager mFragmentManager = getSupportFragmentManager();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        /* Debug only
        ViewServer.get(this).addWindow(this);
        */

        if (BuildVersion.type == BuildVersion.Type.FREE) {
            // Créez l'objet adView.
            AdView lAdView = (AdView) findViewById(R.id.adView);
            // Initiez une demande générique.
            AdRequest adRequest = new AdRequest.Builder().build();
            // Chargez l'objet adView avec la demande d'annonce.
            lAdView.loadAd(adRequest);
        }

        // Variable contenant la chaîne recherchée par l'utilisateur
        String lSearchQuery = "";
        Intent lIntent = getIntent();
        if (Intent.ACTION_SEARCH.equals(lIntent.getAction())) {
            mIsSearchActivity = true;
            lSearchQuery = "%" + lIntent.getStringExtra(SearchManager.QUERY) + "%";
        }

        Fragment lMainFragment;
        Fragment lSecondaryFragment;
        FragmentTransaction lFragmentTransaction = mFragmentManager.beginTransaction();

        if (findViewById(R.id.secondary_fragment_container) != null) {
            mIsDualPane = true;
        }

        if (savedInstanceState != null) {
            lMainFragment = mFragmentManager.getFragment(savedInstanceState, Consts.MAIN_FRAGMENT);
            lSecondaryFragment = mFragmentManager.getFragment(savedInstanceState, Consts.SECONDARY_FRAGMENT);

            lFragmentTransaction.replace(R.id.main_fragment_container, lMainFragment);

            if (mIsDualPane && lSecondaryFragment != null) {
                lFragmentTransaction.replace(R.id.secondary_fragment_container, lSecondaryFragment);
                hideWelcomeMessage();
            }

        } else {

            if (findViewById(R.id.main_fragment_container) != null) {

                // 1er chargement de l'activité (demarrage de l'appli ou recherche)
                lMainFragment = new ProducteurListFragment();
                Bundle args = new Bundle();
                args.putString(Consts.PRODUCTEUR_QUERY, lSearchQuery);
                lMainFragment.setArguments(args);

                lFragmentTransaction.add(R.id.main_fragment_container, lMainFragment);
            }

            if (mIsDualPane && !mIsSearchActivity) {
                displayWelcomeMessage();
            } else if (mIsDualPane) {
                hideWelcomeMessage();
            }
        }
        lFragmentTransaction.commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onActionBarHomeButtonClick();
                return true;
            case R.id.actionbar_premium:
                if (BuildVersion.type == BuildVersion.Type.FREE) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=fr.capsuleaube.android"));
                    startActivity(intent);
                    return true;
                }

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onProducteurSelected(Producteur pProducteur) {

        hideWelcomeMessage();

        CapsulePhotoFragment lCapsulePhotoFragment = new CapsulePhotoFragment();

        Bundle args = new Bundle();
        args.putParcelable(Consts.PRODUCTEUR_BEAN, pProducteur);
        lCapsulePhotoFragment.setArguments(args);

        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if (mIsDualPane) {
            ft.replace(R.id.secondary_fragment_container, lCapsulePhotoFragment);
        } else {
            ft.replace(R.id.main_fragment_container, lCapsulePhotoFragment);
        }
        ft.addToBackStack(null);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
    }

    @Override
    public void onPhotoSelected(Producteur pProducteur, int pCapsuleId) {
        CapsuleDetailFragment lCapsuleDetailFragment = new CapsuleDetailFragment();

        Bundle args = new Bundle();
        args.putParcelable(Consts.PRODUCTEUR_BEAN, pProducteur);
        args.putInt(Consts.CAPSULE_ID, pCapsuleId);
        lCapsuleDetailFragment.setArguments(args);

        FragmentTransaction ft = mFragmentManager.beginTransaction();
        if (mIsDualPane) {
            ft.replace(R.id.secondary_fragment_container, lCapsuleDetailFragment);
        } else {
            ft.replace(R.id.main_fragment_container, lCapsuleDetailFragment);
        }
        ft.addToBackStack(null);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
    }

    @Override
    public void onBackPressed() {
        onActionBarHomeButtonClick();
    }

    private void onActionBarHomeButtonClick() {
        FragmentManager fm = getSupportFragmentManager();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            if (fm.getBackStackEntryCount() > 1) {
                fm.popBackStack();
            } else if (fm.getBackStackEntryCount() == 1 && !mIsSearchActivity) {
                fm.popBackStack();
                actionBar.setDisplayHomeAsUpEnabled(false);
            } else if (fm.getBackStackEntryCount() == 1) {
                fm.popBackStack();
            } else if (fm.getBackStackEntryCount() == 0) {
                finish();
            } else {
                actionBar.setDisplayHomeAsUpEnabled(false);
            }
        }
    }

    private void displayWelcomeMessage() {
        // Affichage du message d'accueil
        if (mIsDualPane) {
            View lWelcomeView = findViewById(R.id.welcome_string);

            if (lWelcomeView != null) {
                lWelcomeView.setVisibility(View.VISIBLE);
            }
        }
    }

    private void hideWelcomeMessage() {
        // Désactivation du message d'accueil
        if (mIsDualPane) {
            View lWelcomeView = findViewById(R.id.welcome_string);

            if (lWelcomeView != null) {
                lWelcomeView.setVisibility(View.GONE);
            }
        }
    }

    public void refreshActivity(View v) {
        if (android.os.Build.VERSION.SDK_INT >= 11) {
            super.recreate();
        } else {
            Intent lIntent = getIntent();
            finish();
            startActivity(lIntent);
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mFragmentManager.findFragmentById(R.id.main_fragment_container) != null) {
            mFragmentManager.putFragment(outState, Consts.MAIN_FRAGMENT, mFragmentManager.findFragmentById(R.id.main_fragment_container));
        }

        if (mIsDualPane && mFragmentManager.findFragmentById(R.id.secondary_fragment_container) != null) {
            mFragmentManager.putFragment(outState, Consts.SECONDARY_FRAGMENT, mFragmentManager.findFragmentById(R.id.secondary_fragment_container));
        }
    }

    /* Debug Only
    @Override
    public void onDestroy() {
        super.onDestroy();
        ViewServer.get(this).removeWindow(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        ViewServer.get(this).setFocusedWindow(this);
    }
    */
}
